<?php
defined('OA_LIB_PATH') || define('OA_LIB_PATH', '/opt/op/OALib');
defined('OPEN_LIB_PATH') || define('OPEN_LIB_PATH', '/opt/op/OpenLib');

require_once 'OaLogic.php';
require_once OA_LIB_PATH . '/inner/service/OAApi.php';
require_once OA_LIB_PATH . '/inner/service/OASApi.php';
require_once OPEN_LIB_PATH . '/open/models/OaAppModel.php';

class OaAppKeyLogic extends OaLogic
{
	    
    /**
     * 上传应用公钥
     * @param int $appId
     * @param string $key
     * @param int $env
     * @return boolean
     */
    public static function uploadAppPubKey($appId, $key, $env)
    {
        $logger = self::getLogger();
        $appModel = new OaAppModel($env, $logger);
        return $appModel->modifyApp($appId, array(
            'app_pub_key' => $key
        ));
    }
    
    /**
     * 是否已上传应用公钥
     * @param int $appId
     * @param int $env
     * @return boolean
     */
    public static function isUploadedAppPubKey($appId, $env)
    {
        $logger = self::getLogger();
        $appModel = new OaAppModel($env, $logger);
        $app = $appModel->getApp($appId);
        if (is_array($app) && !empty($app['app_pub_key'])) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 获取盛大公钥
     * @param int $appId
     * @param int $env
     * @return string|boolean
     */
    public static function downloadSndaPubKey($appId, $env)
    {
        $logger = self::getLogger();
        $appModel = new OaAppModel($env, $logger);
        $app = $appModel->getApp($appId);
        if (!is_array($app)) {
            $logger->err("app not exists: app-$appId");
            return false;
        }
        $message = '';
        $sndaPubKey = OASApi::rsa(&$message, array(
            'spId' => $app['company_id'],
            'appId' => $appId
        ), 'select', $env);
        if ($sndaPubKey === false) {
            $logger->err("get snda pub key failed: message-$message");
            return false;
        }
        return $appModel->modifyApp($appId, array(
            'snda_pub_key' => $sndaPubKey
        ));
    }
    
    /**
     * 是否已下载盛大公钥
     * @param int $appId
     * @param int $env
     * @return boolean
     */
    public function isDownloadedSndaPubKey($appId, $env)
    {
        $logger = self::getLogger();
        $appModel = new OaAppModel($env, $logger);
        $app = $appModel->getApp($appId, array('snda_pub_key'));
        if (is_array($app) && !empty($app['snda_pub_key'])) {
            return true;
        } else {
            return false;
        }
    }
}